import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import '../utils/logger.dart';

/// 签名服务
/// 负责生成各平台的请求签名
class SignatureService {
  static const String _damaiSecret = 'damai_secret_key';
  static const String _maoyanSecret = 'maoyan_secret_key';

  /// 生成大麦签名
  Future<String> generateSignature({
    required Map<String, dynamic> params,
    required String deviceId,
    required int timestamp,
  }) async {
    try {
      // 大麦签名算法
      final sortedKeys = params.keys.toList()..sort();
      final signString = sortedKeys
          .map((key) => '$key=${params[key]}')
          .join('&');
      
      final fullString = '$signString&deviceId=$deviceId&timestamp=$timestamp&secret=$_damaiSecret';
      
      final bytes = utf8.encode(fullString);
      final digest = md5.convert(bytes);
      
      return digest.toString().toUpperCase();
    } catch (e) {
      AppLogger.error('Generate Damai signature failed', e);
      return _generateFallbackSignature(deviceId, timestamp);
    }
  }

  /// 生成猫眼签名
  Future<String> generateMaoyanSignature({
    required String data,
    required String deviceId,
    required int timestamp,
    required String nonce,
  }) async {
    try {
      // 猫眼签名算法（简化版本）
      final signData = '$data&deviceId=$deviceId&timestamp=$timestamp&nonce=$nonce&secret=$_maoyanSecret';
      
      final bytes = utf8.encode(signData);
      final digest = sha256.convert(bytes);
      
      return digest.toString();
    } catch (e) {
      AppLogger.error('Generate Maoyan signature failed', e);
      return _generateFallbackSignature(deviceId, timestamp);
    }
  }

  /// 生成通用签名
  Future<String> generateGenericSignature({
    required String platform,
    required Map<String, dynamic> params,
    required String deviceId,
    required int timestamp,
  }) async {
    switch (platform.toLowerCase()) {
      case 'damai':
        return await generateSignature(
          params: params,
          deviceId: deviceId,
          timestamp: timestamp,
        );
      case 'maoyan':
        final nonce = Random().nextInt(999999).toString().padLeft(6, '0');
        final data = params.entries
            .map((e) => '${e.key}=${e.value}')
            .join('&');
        return await generateMaoyanSignature(
          data: data,
          deviceId: deviceId,
          timestamp: timestamp,
          nonce: nonce,
        );
      default:
        return _generateFallbackSignature(deviceId, timestamp);
    }
  }

  /// 验证签名
  Future<bool> verifySignature({
    required String signature,
    required String platform,
    required Map<String, dynamic> params,
    required String deviceId,
    required int timestamp,
  }) async {
    try {
      final expectedSignature = await generateGenericSignature(
        platform: platform,
        params: params,
        deviceId: deviceId,
        timestamp: timestamp,
      );
      
      return signature.toLowerCase() == expectedSignature.toLowerCase();
    } catch (e) {
      AppLogger.error('Verify signature failed', e);
      return false;
    }
  }

  /// 生成备用签名
  String _generateFallbackSignature(String deviceId, int timestamp) {
    final random = Random();
    final randomString = List.generate(16, (index) => 
        random.nextInt(16).toRadixString(16)).join();
    
    final fallbackData = '$deviceId$timestamp$randomString';
    final bytes = utf8.encode(fallbackData);
    final digest = md5.convert(bytes);
    
    return digest.toString().toUpperCase();
  }

  /// 生成请求ID
  String generateRequestId() {
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final random = Random().nextInt(999999);
    return '${timestamp}_$random';
  }

  /// 生成随机字符串
  String generateRandomString(int length) {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = Random();
    return List.generate(length, (index) => 
        chars[random.nextInt(chars.length)]).join();
  }

  /// 计算文件哈希
  String calculateFileHash(List<int> bytes) {
    final digest = sha256.convert(bytes);
    return digest.toString();
  }

  /// 生成HMAC签名
  String generateHmacSignature(String data, String key) {
    final keyBytes = utf8.encode(key);
    final dataBytes = utf8.encode(data);
    final hmac = Hmac(sha256, keyBytes);
    final digest = hmac.convert(dataBytes);
    return digest.toString();
  }
}